package Sorters;

import org.apache.log4j.Logger;

/**
 *
 * @author Admin
 */
public class CountingSort implements DataSorter<Integer> {

    private static final Logger log = Logger.getLogger(CountingSort.class);

    @Override
    public Integer[] sort(Integer[] data) {

        if (data == null) {
            return null;
        }
        if (data.length == 0) {
            return data;
        }
        Integer[] temp = new Integer[data.length];
        System.arraycopy(data, 0, temp, 0, data.length);
        int max = temp[0];
        for (int i = 1; i < temp.length; i++) {

            if (temp[i] > max) {
                max = temp[i];
            }
        }
        countSort(temp, max);
        return temp;
    }

    private void countSort(Integer[] data, int max) {
        int b = 0;
        Integer[] temp = new Integer[max + 1];
        for (int i = 0; i < max; i++) {
            temp[i] = 0;
        }
        for (int i = 0; i < data.length - 1; i++) {
            temp[data[i]]++;
        }
        for (int j = 0; j < max; j++) {
            for (int i = 0; i < temp[j]; i++) {
                data[b] = j;
                b++;
            }
        }
    }
}
